package mysql

import (
	"gorm.io/gorm"
	"home-info-site/userrpc/userrpc"
)

type Product struct {
	gorm.Model
	UserId       int32   `gorm:"type:int(11);not null"`
	ProductName  string  `gorm:"type:varchar(30);not null"`
	ProductStock int32   `gorm:"type:int(11);not null"`
	ProductPrice float32 `gorm:"type:decimal(10,2);not null"`
}

func (p *Product) ProductAdd(db *gorm.DB) error {
	return db.Debug().Create(p).Error
}

/*
SELECT

	users.username ,
	products.product_name ,
	products.product_price ,
	products.product_stock

FROM

	users
	LEFT JOIN products ON users.id = products.user_id
*/
func ProductList(db *gorm.DB, list []*userrpc.ProductList, id int64) []*userrpc.ProductList {
	db.Debug().Model(&User{}).
		Select(
			"users.username",
			"products.product_name",
			"products.product_price",
			"products.product_stock",
		).
		Joins("LEFT JOIN products ON users.id = products.user_id").
		Where("products.user_id=?", id).
		Find(&list)
	return list
}

func ProductDetail(db *gorm.DB, list *userrpc.ProductDetailResponse, id int64) *userrpc.ProductDetailResponse {
	db.Debug().Model(&User{}).
		Select(
			"users.username",
			"products.product_name",
			"products.product_price",
			"products.product_stock",
			"products.id product_id",
		).
		Joins("LEFT JOIN products ON users.id = products.user_id").
		Where("products.id=?", id).
		Find(&list)
	return list
}
